using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

namespace AntEater.Runtime.ExceptionHandling
{
    /// <summary>
    /// An exception handler for the Enterprise Library
    /// </summary>
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class OutputExceptionHandler : IExceptionHandler
    {
        private NameValueCollection _values;

        /// <summary>
        /// Initializes a new instance of the <see cref="OutputExceptionHandler"/> class.
        /// </summary>
        /// <param name="values">The values.</param>
        public OutputExceptionHandler(NameValueCollection values)
        {
            this._values = values;
        }

        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="handlingInstanceId">The handling instance id.</param>
        /// <returns>The handled Exception</returns>
        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            // Check method parameters
            if (exception == null) {
                throw new ArgumentNullException("exception");
            }

            // Write error message to the output
            AntEaterRuntime.Instance.Output.WriteLine(BuildMessage(exception));
            return exception;
        }

        /// <summary>
        /// Builds the message.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <returns></returns>
        private string BuildMessage(Exception exception)
        {
            // Create string builder and append teh exception message
            StringBuilder result = new StringBuilder();
            result.Append(exception.Message);

            // Append the values Collection
            if ((this._values != null) && (this._values.Count > 0)) {
                result.Append(Environment.NewLine);
                result.Append(Environment.NewLine);
                result.Append(this._values.ToString());
            }

            return result.ToString();
        }
    }
}
